const CartHttp = require("../../models/CartHttp")
Page({
    data:{
        carts:[],
        allChecked:"",
        sum:""
    },
    async onLoad(){
        var res = await CartHttp.getCart();
        var allChecked = res.data.every(item=>{
            return item.isSelected;
        })
        // console.log(allChecked)
        this.setData({
            carts:res.data,
            allChecked
        })
        this.handleSum()
    },
    handleNum(event){
        /* 通过id值,找到数组中对应的项目,将项目中的productCount更改 */
        // console.log(event.detail)
        var carts = this.data.carts;
        var {aid} = event.currentTarget.dataset;
        carts.forEach(item=>{
            if(item.id == aid)[
                item.productCount =  event.detail
            ]
        })
        this.setData({
            carts
        })
        this.handleSum()

    },
    handleSelect(event){
        console.log(event.detail)
        var carts = this.data.carts;
        var {aid} = event.currentTarget.dataset;
        carts.forEach(item=>{
            if(item.id == aid)[
                item.isSelected =  event.detail
            ]
        })
        /* 更改item的check,allCheced */
        var allChecked = carts.every(item=>{
            return item.isSelected;
        })
        this.setData({
            carts,
            allChecked
        })
        this.handleSum()
    },
    handleAll(event){
        console.log(event.detail);
        var carts = this.data.carts;
        carts.forEach(item=>{
            item.isSelected = event.detail;
        })
        this.setData({
            allChecked:event.detail,
            carts
        })
        this.handleSum()
    },
    handleSum(){
        var sum = 0;
        var carts = this.data.carts;
        carts.forEach(item=>{
            if(item.isSelected){
                sum += (item.productPrice)*(item.productCount)   
             }
        })
        this.setData({
            sum:sum*100
        })
    }

})